﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using roster.Domain;

namespace roster.UI
{
    public partial class PlayerListControl : ListBox
    {
        public PlayerListControl()
        {
            InitializeComponent();
        }

        [Browsable(false)]
        public IPlayer SelectedPlayer
        {
            get
            {
                var decorator = ((PlayerDisplayDecorator) SelectedItem);
                return decorator == null ? null : decorator.Player;
            }
            set { SelectedItem = (value == null ? null : FindPlayerDecorator(value)); }
        }

        [Browsable(false)]
        public IEnumerable<IPlayer> SelectedPlayers
        {
            get { return SelectedItems.Cast<PlayerDisplayDecorator>().Select(x => x.Player); }
            set
            {
                SelectedItems.Clear();
                foreach (IPlayer player in value)
                {
                    SelectedItems.Add(FindPlayerDecorator(player));
                }
            }
        }

        public bool HasSelectedPlayers
        {
            get { return SelectedPlayers.Count() > 0; }
        }

        private PlayerDisplayDecorator FindPlayerDecorator(IPlayer player)
        {
            return Items.Find<PlayerDisplayDecorator>(x => x.Player == player);
        }

        public void AddPlayers(IEnumerable<IPlayer> players)
        {
            Items.Clear();
            int count = 1;
            Items.AddRange(players.Select(x => new PlayerDisplayDecorator(count++, x)).ToArray());
        }
    }
}